package cool.xinya.ess.security;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;

/**
 * redis缓存
 *
 * @author wangxiaolong
 * @date 2019/6/27.
 */
public class RedisCache<K, V> implements Cache<K, V> {

    private final RedisTemplate redisTemplate;
    private final HashOperations<String, K, V> cacheOperations;

    public RedisCache(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        cacheOperations = redisTemplate.opsForHash();
    }

    @Override
    public V get(K key) throws CacheException {
        return cacheOperations.get("cache:", key);
    }

    @Override
    public V put(K key, V value) throws CacheException {
        cacheOperations.put("cache:", key, value);
        return value;
    }

    @Override
    public V remove(K key) throws CacheException {
        if (key instanceof ShiroUser) {
            String username = ((ShiroUser) key).getLoginName();
            cacheOperations.delete("cache:", username);
        }
        return null;
    }

    @Override
    public void clear() throws CacheException {

    }

    @Override
    public int size() {
        return keys().size();
    }

    @Override
    public Set<K> keys() {
        return redisTemplate.keys("cache:");
    }

    @Override
    public Collection<V> values() {
        return null;
    }
}
